package org.fioma.tree.suffixTree.bytes;

import org.fioma.tree.bytes.Tools;
import org.fioma.tree.suffixTree.SuffixTree;

public class SuffixTreeBytes implements SuffixTree<byte[]> {

	int k;
	SuffixRootBytes root;

	public SuffixTreeBytes(int k) {
		this.k = k;
		this.root = new SuffixRootBytes();
	}

	public void addSuffixes(byte[] word) {
		LeafSuffixNodeBytes lastLeaf = root.addWord(word);

		for (int j = 1; lastLeaf != null; j++) {
			// find w[j..i-1]
			InternalSuffixNodeBytes parentLastLeaf = lastLeaf.getParent();
			byte[] lastLeafLabel = lastLeaf.getLabel();
			if (parentLastLeaf.isRoot()) {
				lastLeaf = parentLastLeaf.addWord(Tools.substring(lastLeafLabel, 1));
			} else {
				InternalSuffixNodeBytes suffixLink = parentLastLeaf.getSuffixLink();
				if (suffixLink != null) {
					lastLeaf = suffixLink.addWord(lastLeafLabel);
				} else {
					byte[] parentLastLeafLabel = parentLastLeaf.getLabel();
					InternalSuffixNodeBytes v = parentLastLeaf.getParent();
					if (v.isRoot()) {
						parentLastLeafLabel = Tools.substring(parentLastLeafLabel, 1);
						lastLeaf = v.addWord(Tools.joinWords(parentLastLeafLabel, lastLeafLabel));
						suffixLink = (InternalSuffixNodeBytes) v.findNode(parentLastLeafLabel);
					} else {
						InternalSuffixNodeBytes sv = v.getSuffixLink();
						lastLeaf = sv.addWord(Tools.joinWords(parentLastLeafLabel, lastLeafLabel));
						suffixLink = (InternalSuffixNodeBytes) sv.findNode(parentLastLeafLabel);
					}
					parentLastLeaf.setSuffixLink(suffixLink);
				}
			}
//			if ((j + k >= word[0]) && lastLeaf != null && (lastLeaf.getParent().getSuffixLink() != null || lastLeaf.getParent().isRoot())) {
//				System.out.println("Get out!");
//				break;
//			}
		}
//		root.addWord(Tools.substring(word, i, 1));
//		}
	}

	@Override
	public SuffixRootBytes getRoot() {
		return root;
	}

}
